package Zoo.handler;

import Zoo.util.InsertUtil;
import Zoo.view.registerview.RegisterView;


import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.sql.SQLException;

/**
 * 注册界面处理类
 */

public class RegisterHandler extends KeyAdapter implements ActionListener {
    private RegisterView registerView;

    public RegisterHandler(RegisterView registerView) {
        this.registerView = registerView;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        JButton jButton = (JButton) e.getSource();
        String text = jButton.getText();
        if ("重置".equals(text)) {
            registerView.getUserTxt().setText("");
            registerView.getPwdField().setText("");
            registerView.getPhoneTxt().setText("");
        } else if ("注册".equals(text)) {
            try {
                register();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
    }

    private void register() throws SQLException {
        String user = registerView.getUserTxt().getText();
        char[] chars = registerView.getPwdField().getPassword();
        String phone = registerView.getPhoneTxt().getText();
        //校验密码和用户名是否为空
        if (user == null || "".equals(user.trim()) || chars == null || phone == null || "".equals(phone.trim())) {
            JOptionPane.showMessageDialog(registerView, "用户名，密码和联系电话必填");
            return;
        }
        String pwd = new String(chars);
        System.out.println(user + ":" + pwd);
        System.out.println(phone);


        //插入数据（注册用户）
        InsertUtil in = new InsertUtil();
        in.insert(user, pwd, phone);
        JOptionPane.showMessageDialog(registerView, "已注册成功，请重新打开窗口并登录");
    }

    //注册的时候可以按注册按钮，也可以按回车
    @Override
    public void keyPressed(KeyEvent e) {
        e.getKeyCode();
        if (KeyEvent.VK_ENTER == e.getKeyCode()) {
            try {
                register();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
    }
}
